from django.shortcuts import render, redirect, HttpResponse
from . import models
from .forms import UserForm, RegisterForm
import hashlib
# Create your views here.
def index(request):
    pass
    return render(request, 'login/index.html')


def login(request):
    if request.session.get('is_login', None):
        return redirect('/index')

    if request.method == "POST":
        login_from = UserForm(request.POST)
        message = "请检查填写的内容！"
        if login_from.is_valid():
            # username = request.POST.get('username', None)
            # password = request.POST.get('password', None)
            # message = "所有字段都必须填写！"
            username = login_from.cleaned_data['username']
            password = login_from.cleaned_data['password']
            try:
                user = models.User.objects.get(name=username)
                if user.password == hash_code(password):
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    return redirect('/index')
                else:
                    message = "密码不正确！"
            except:
                message = "用户不存在！"
        return render(request, 'login/login.html', locals())

    login_form = UserForm()
    return render(request, 'login/login.html', locals())
'''
对于非POST方法发送数据时，比如GET方法请求页面，返回空的表单，让用户可以填入数据；
对于POST方法，接收表单数据，并验证；
使用表单类自带的is_valid()方法一步完成数据验证工作；
验证成功后可以从表单对象的cleaned_data数据字典中获取表单的具体值；
如果验证不通过，则返回一个包含先前数据的表单给前端页面，方便用户修改。也就是说，它会帮你保留先前填写的数据内容，而不是返回一个空表！
Python内置了一个locals()函数，它返回当前所有的本地变量字典，我们可以偷懒的将这作为render函数的数据字典参数值，
就不用费劲去构造一个形如{'message':message, 'login_form':login_form}的字典了。
这样做的好处当然是大大方便了我们，但是同时也可能往模板传入了一些多余的变量数据，造成数据冗余降低效率。
'''

def register(request):
    if request.session.get('is_login', None):
        # 登录状态不允许注册
        return redirect('/index/')
    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():
            # 获取数据
            username = register_form.cleaned_data['username']
            password1 = register_form.cleaned_data['password1']
            password2 = register_form.cleaned_data['password2']
            email = register_form.cleaned_data['email']
            sex = register_form.cleaned_data['sex']
            if password1 != password2:
                # 判断两次密码是否相同
                message = "两次输入的密码不一致！"
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = models.User.objects.filter(name=username)
                if same_name_user:
                    message = '用户已经存在，请重新选择用户名！'
                    return render(request, 'login/register.html', locals())
                same_email_user = models.User.objects.filter(email=email)
                if same_email_user:
                    message = "该邮箱地址已被注册，请使用其他邮箱！"
                    return render(request, 'login/register.html', locals())
                # 如果所有信息都符合要求，就创建新用户
                new_user = models.User.objects.create()
                new_user.name = username
                new_user.password = hash_code(password1)
                new_user.email = email
                new_user.sex = sex
                new_user.save()
                # 注册成功后跳转到登录页面
                return redirect('/login/')
    register_form = RegisterForm()
    return render(request, 'login/register.html', locals())


def logout(request):
    if not request.session.get('is_login', None):
        # 如果没有登录session信息
        return redirect('/index/')
    request.session.flush()
    # 或者使用单条删除语句删除指定信息
    # del request.session['is_login']
    # del request.session['user_id']
    # del request.session['user_name']
    return redirect('/index/')


def hash_code(s, salt='mysite'):
    # 加盐处理
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())
    # update方法只接受bytes类型
    return h.hexdigest()